package cn.tedu.coolshark.filter;

import cn.tedu.coolshark.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "MyFilter",urlPatterns = {"/insertProduct.html","/admin.html"})
public class MyFilter implements Filter {
    //当过滤器初始化时执行的方法
    public void init(FilterConfig config) throws ServletException {
    }
    //当过滤器销毁时执行的方法
    public void destroy() {
    }
    //当接受到请求时会执行此方法,需要在此方法中判断是否满足条件,如果满足则可以访问资源文件,不满足则拦截
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //强转,将父类型转为子类型
        HttpServletRequest st = (HttpServletRequest) request;
        HttpServletResponse se = (HttpServletResponse) response;
        //得到会话对象
        HttpSession session = st.getSession();
        //从会话对象当中得到登录成功之后保存的用户对象
        User user = (User)session.getAttribute("user");
        if (user != null) { //登录过
            chain.doFilter(request, response); //放行,允许访问资源
        }else { //没登录过
            se.sendRedirect("/login.html"); //重定向,让客户端重新跳转到登录页面进行登录
        }
        System.out.println("过滤器执行了!");
    }
}
